package router

import (
	systemController "gitee.com/wangshh_123/cross-pay-go/src/controller/system"
	"gitee.com/wangshh_123/cross-pay-go/src/middleware"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/hlPay"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// SetupAdminRouter 设置管理员相关路由
func SetupAdminRouter(router *gin.RouterGroup, db *gorm.DB, photonPayClient *photonpay.PhotonPayClient, hlPayClient *hlPay.HlPayClient) {
	// 创建管理员控制器
	adminController := systemController.NewAdminController(db, photonPayClient, hlPayClient)

	// 创建海连管理员控制器
	hlAdminController := systemController.NewHlAdminController(db, hlPayClient)

	// 创建用户开卡费用配置控制器
	userCardFeeConfigController := systemController.NewUserCardFeeConfigController(db)

	// 创建平台切换控制器
	platformSwitchController := systemController.NewPlatformSwitchController()

	// 管理员路由组
	admin := router.Group("/admin")
	{
		// 角色管理路由组
		rolesGroup := admin.Group("/roles")
		rolesGroup.Use(middleware.AuthMiddleware(), middleware.AdminMiddleware())
		{
			// 创建角色
			rolesGroup.POST("", adminController.CreateRole)

			// 获取所有角色
			rolesGroup.GET("", adminController.GetRoles)

			// 更新角色
			rolesGroup.PUT("/:id", adminController.UpdateRole)

			// 删除角色
			rolesGroup.DELETE("/:id", adminController.DeleteRole)
		}

		// 用户角色管理路由组
		userRolesGroup := admin.Group("/user-roles")
		userRolesGroup.Use(middleware.AuthMiddleware(), middleware.AdminMiddleware())
		{
			/*
				为用户分配角色
				POST /api/v1/admin/user-roles
				Headers:
					Authorization: Bearer <token>
				Body:
				{
					"user_id": 1,
					"role_id": 1
				}
			*/
			userRolesGroup.POST("", adminController.AssignRoleToUser)

			/*
				移除用户角色
				DELETE /api/v1/admin/user-roles/:userId/:roleId
				Headers:
					Authorization: Bearer <token>
			*/
			userRolesGroup.DELETE("/:userId/:roleId", adminController.RemoveRoleFromUser)

			/*
				获取用户的所有角色
				GET /api/v1/admin/user-roles/:userId
				Headers:
					Authorization: Bearer <token>
			*/
			userRolesGroup.GET("/:userId", adminController.GetUserRoles)
		}

		// 平台切换管理路由组
		platformSwitchGroup := admin.Group("/platform-switch")
		platformSwitchGroup.Use(middleware.AuthMiddleware(), middleware.AdminMiddleware())
		{
			/*
				管理员检查用户平台切换约束
				GET /api/v1/admin/platform-switch/check/:user_id
				Headers:
					Authorization: Bearer <token>
			*/
			platformSwitchGroup.GET("/check/:user_id", platformSwitchController.AdminCheckUserSwitchConstraints)

			/*
				管理员执行用户平台切换
				POST /api/v1/admin/platform-switch/execute/:user_id
				Headers:
					Authorization: Bearer <token>
				Body:
				{
					"target_platform": "hlpay",
					"confirm": true,
					"reason": "管理员协助切换平台"
				}
			*/
			platformSwitchGroup.POST("/execute/:user_id", platformSwitchController.AdminExecuteUserPlatformSwitch)

			/*
				获取用户平台切换日志
				GET /api/v1/admin/platform-switch/logs/:user_id
				Headers:
					Authorization: Bearer <token>
				Query Parameters:
					page: 页码，默认1
					page_size: 每页数量，默认10
			*/
			platformSwitchGroup.GET("/logs/:user_id", platformSwitchController.AdminGetUserSwitchLogs)

			/*
				获取用户的所有平台账户状态
				GET /api/v1/admin/platform-switch/accounts/:user_id
				Headers:
					Authorization: Bearer <token>
			*/
			platformSwitchGroup.GET("/accounts/:user_id", platformSwitchController.AdminGetUserPlatformAccounts)
		}

		// 矩阵转账路由组
		matrixGroup := admin.Group("/matrix")
		matrixGroup.Use(middleware.AuthMiddleware(), middleware.AdminMiddleware())
		{
			/*
				管理员执行矩阵转账
				POST /api/v1/admin/matrix/transfer
				Headers:
					Authorization: Bearer <token>
				Body:
				{
					"currency": "USD",
					"matrixAccount": "account123",
					"transferAmount": "100.00",
					"transferType": "transfer_in"
				}
			*/
			matrixGroup.POST("/transfer", adminController.AdminMatrixTransfer)
			matrixGroup.POST("/transfer-tt", adminController.AdminMatrixTransferTT)

			/*
				获取单个矩阵账户信息
				GET /api/v1/admin/matrix/accounts/:id
				Headers:
					Authorization: Bearer <token>
			*/
			matrixGroup.GET("/accounts/:id", adminController.GetMatrixAccount)

			/*
				获取矩阵账户列表
				GET /api/v1/admin/matrix/accounts
				Headers:
					Authorization: Bearer <token>
				Query Parameters:
					page: 页码，默认1
					page_size: 每页数量，默认10
					status: 账户状态筛选
					matrix_account: 账户号模糊搜索
					user_id: 用户ID筛选
			*/
			matrixGroup.GET("/accounts", adminController.GetMatrixAccounts)

			// 新增查询金额账户列表接口
			matrixGroup.GET("/account-list", adminController.GetAccountList)

			// 新增获取转账记录列表接口
			matrixGroup.GET("/transfer-records", adminController.GetAdminTransferRecords)

			/*
				根据matrix账户获取账户资金
				GET /api/v1/admin/matrix/account-balance
				Headers:
					Authorization: Bearer <token>
				Query Parameters:
					matrix_account: matrix账户（必填）
					currency: 货币类型
					account_no: 账户号
					member_id: 会员ID
					account_type: 账户类型
			*/
			matrixGroup.GET("/account-balance", adminController.GetAccountBalanceByMatrixAccount)

			/*
				根据matrix账户获取交易明细
				GET /api/v1/admin/matrix/account-history
				Headers:
					Authorization: Bearer <token>
				Query Parameters:
					matrix_account: matrix账户（必填）
					page: 页码，默认1
					page_size: 每页数量，默认10
					start_time: 开始时间
					end_time: 结束时间
					currency: 货币类型
					account_type: 账户类型
					account_no: 账户号
					member_id: 会员ID
			*/
			matrixGroup.GET("/account-history", adminController.GetAccountHistoryByMatrixAccount)

			/*
				根据matrix账户获取卡列表
				GET /api/v1/admin/matrix/cards
				Headers:
					Authorization: Bearer <token>
				Query Parameters:
					matrix_account: matrix账户（必填）
					page: 页码，默认1
					page_size: 每页数量，默认10
					card_bin: 卡BIN
					created_at_start: 创建开始时间
					created_at_end: 创建结束时间
					card_type: 卡片类型
					card_form_factor: 卡片形式
					card_status: 卡片状态
			*/
			matrixGroup.GET("/cards", adminController.GetCardListByMatrixAccount)

			/*
				获取矩阵账户列表（TT）
				GET /api/v1/admin/matrix/accounts-tt
				Headers:
					Authorization: Bearer <token>
			*/
			matrixGroup.GET("/accounts-tt", adminController.GetMatrixAccountListRaw)
		}

		// 海连管理路由组
		hlpayGroup := admin.Group("/hlpay")
		hlpayGroup.Use(middleware.AuthMiddleware(), middleware.AdminMiddleware())
		{
			/*
				海连管理员执行矩阵转账
				POST /api/v1/admin/hlpay/transfer
				Headers:
					Authorization: Bearer <token>
				Body:
				{
					"currency": "USD",
					"platformAccount": "HL-USD123456",
					"transferAmount": "100.00",
					"transferType": "transfer_in",
					"remark": "转账备注"
				}
			*/
			hlpayGroup.POST("/transfer", hlAdminController.HlAdminMatrixTransfer)

			/*
				获取HlPay账户余额
				GET /api/v1/admin/hlpay/balance
				Headers:
					Authorization: Bearer <token>
				Query Parameters:
					matrix_account: matrix账户（必填）
			*/
			hlpayGroup.GET("/balance", hlAdminController.GetHlPayAccountBalance)

			/*
				管理员查询用户交易记录
				GET /api/v1/admin/hlpay/user-transactions
				Headers:
					Authorization: Bearer <token>
				Query Parameters:
					user_id: 用户ID（可选，与matrix_account二选一）
					matrix_account: MatrixAccount（可选，与user_id二选一）
					pageIndex: 页码（可选，默认1）
					pageSize: 页面大小（可选，默认10，最大100）
			*/
			hlpayGroup.GET("/user-transactions", hlAdminController.GetUserTransactions)

			/*
				管理员通过MatrixAccount查询用户交易记录
				GET /api/v1/admin/hlpay/user-transactions/matrix/:matrix_account
				Headers:
					Authorization: Bearer <token>
				Path Parameters:
					matrix_account: MatrixAccount
				Query Parameters:
					pageIndex: 页码（可选，默认1）
					pageSize: 页面大小（可选，默认10，最大100）
			*/
			hlpayGroup.GET("/user-transactions/matrix/:matrix_account", hlAdminController.GetUserTransactionsByMatrixAccount)
		}

		// 开卡统计路由组
		cardStatsGroup := admin.Group("/card-stats")
		cardStatsGroup.Use(middleware.AuthMiddleware(), middleware.AdminMiddleware())
		{
			/*
				获取统计数据（包含开卡和转账统计）
				GET /api/v1/admin/card-stats/statistics
				Headers:
					Authorization: Bearer <token>
				Query Parameters:
					start_date: 开始日期（可选，默认30天前）
					end_date: 结束日期（可选，默认今天）
					platform: 平台标识（可选，如 photonpay）
					currency: 货币类型（可选）
			*/
			cardStatsGroup.GET("/statistics", adminController.GetStatistics)
			// 新增：读取指定日期的trades_xxx.xlsx文件内容
			cardStatsGroup.POST("/read-files-by-dates", adminController.ReadFilesByDates)
		}

		// 余额管理路由组
		balanceGroup := admin.Group("/balance")
		balanceGroup.Use(middleware.AuthMiddleware(), middleware.AdminMiddleware())
		{
			/*
				检查余额异常
				GET /api/v1/admin/balance/check-anomalies
				Headers:
					Authorization: Bearer <token>
			*/
			balanceGroup.GET("/check-anomalies", adminController.CheckBalanceAnomalies)

			/*
				修复余额异常
				POST /api/v1/admin/balance/fix-anomalies
				Headers:
					Authorization: Bearer <token>
			*/
			balanceGroup.POST("/fix-anomalies", adminController.FixBalanceAnomalies)

			/*
				运行余额审计
				POST /api/v1/admin/balance/audit
				Headers:
					Authorization: Bearer <token>
			*/
			balanceGroup.POST("/audit", adminController.RunBalanceAudit)
		}

		// 数据看板路由组
		dashboardGroup := admin.Group("/dashboard")
		dashboardGroup.Use(middleware.AuthMiddleware(), middleware.AdminMiddleware())
		{
			/*
				获取交易数据看板
				GET /api/v1/admin/dashboard/transaction
				Headers:
					Authorization: Bearer <token>
				Query Parameters:
					start_date: 开始日期（可选，默认30天前）
					end_date: 结束日期（可选，默认今天）
			*/
			dashboardGroup.GET("/transaction", adminController.GetTransactionDashboard)

			/*
				获取交易统计数据列表
				GET /api/v1/admin/dashboard/transaction-stats
				Headers:
					Authorization: Bearer <token>
				Query Parameters:
					month: 月份（可选，格式：YYYY-MM）
					start_date: 开始日期（可选）
					end_date: 结束日期（可选）
					limit: 限制数量（可选）
					offset: 偏移量（可选）
			*/
			dashboardGroup.GET("/transaction-stats", adminController.GetTransactionStats)

			/*
				根据月份获取交易统计数据
				GET /api/v1/admin/dashboard/transaction-stats/month/:month
				Headers:
					Authorization: Bearer <token>
				Path Parameters:
					month: 月份，支持格式：
						- 6 (当前年份的6月)
						- 06 (当前年份的6月)
						- 2025-6 (2025年6月)
						- 2025-06 (2025年6月)
			*/
			dashboardGroup.GET("/transaction-stats/month/:month", adminController.GetTransactionStatsByMonth)

			/*
				根据年份和月份获取交易统计数据
				GET /api/v1/admin/dashboard/transaction-stats/year/:year/month/:month
				Headers:
					Authorization: Bearer <token>
				Path Parameters:
					year: 年份，如 2025
					month: 月份，1-12的数字
			*/
			dashboardGroup.GET("/transaction-stats/year/:year/month/:month", adminController.GetTransactionStatsByYearMonth)

			/*
				获取最新的交易统计数据
				GET /api/v1/admin/dashboard/transaction-stats/latest
				Headers:
					Authorization: Bearer <token>
			*/
			dashboardGroup.GET("/transaction-stats/latest", adminController.GetLatestTransactionStats)

			/*
				根据ID获取交易统计数据
				GET /api/v1/admin/dashboard/transaction-stats/:id
				Headers:
					Authorization: Bearer <token>
			*/
			dashboardGroup.GET("/transaction-stats/:id", adminController.GetTransactionStatsByID)
		}

		// 用户开卡费用配置路由组
		userCardFeeConfigGroup := admin.Group("/user-card-fee-configs")
		userCardFeeConfigGroup.Use(middleware.AuthMiddleware(), middleware.AdminMiddleware())
		{
			// 创建用户卡费配置绑定
			userCardFeeConfigGroup.POST("", userCardFeeConfigController.CreateUserCardFeeConfig)

			// 更新用户卡费配置状态
			userCardFeeConfigGroup.PUT("/:id", userCardFeeConfigController.UpdateUserCardFeeConfig)

			// 获取用户卡费配置
			userCardFeeConfigGroup.GET("/:id", userCardFeeConfigController.GetUserCardFeeConfig)

			// 获取用户卡费配置列表
			userCardFeeConfigGroup.GET("", userCardFeeConfigController.GetUserCardFeeConfigs)

			// 删除用户卡费配置
			userCardFeeConfigGroup.DELETE("/:id", userCardFeeConfigController.DeleteUserCardFeeConfig)

			// 获取指定用户的所有卡费配置
			userCardFeeConfigGroup.GET("/user/:user_id", userCardFeeConfigController.GetUserCardFeeConfigsByUser)

			// 获取用户激活的卡费配置
			userCardFeeConfigGroup.GET("/user/:user_id/active", userCardFeeConfigController.GetUserActiveCardFeeConfigs)
		}

		// 卡费配置路由组
		cardFeeConfigGroup := admin.Group("/card-fee-configs")
		cardFeeConfigGroup.Use(middleware.AuthMiddleware(), middleware.AdminMiddleware())
		{
			// 获取卡费配置列表
			cardFeeConfigGroup.GET("", userCardFeeConfigController.GetCardFeeConfigs)
		}

		// 平台选择配置路由组
		platformSelectionGroup := admin.Group("/platform-selection")
		platformSelectionGroup.Use(middleware.AuthMiddleware(), middleware.AdminMiddleware())
		{
			/*
				获取平台选择配置
				GET /api/v1/admin/platform-selection/config
				Headers:
					Authorization: Bearer <token>
			*/
			platformSelectionGroup.GET("/config", adminController.GetPlatformSelectionConfig)

			/*
				更新平台选择配置
				PUT /api/v1/admin/platform-selection/config
				Headers:
					Authorization: Bearer <token>
				Body:
				{
					"enabled": true,
					"monthly_platforms": {
						"1": "hlpay",
						"2": "photonpay",
						"3": "hlpay",
						"4": "photonpay",
						"5": "hlpay",
						"6": "photonpay",
						"7": "hlpay",
						"8": "photonpay",
						"9": "hlpay",
						"10": "photonpay",
						"11": "hlpay",
						"12": "photonpay"
					},
					"default_platform": "photonpay"
				}
			*/
			platformSelectionGroup.PUT("/config", adminController.UpdatePlatformSelectionConfig)
		}
	}
}
